<?php
declare(strict_types=1);

namespace app\controller\user;

use app\controller\BaseController;
use app\model\{User, LifeServiceConfig};
use app\service\{JutuikeService, LogService, SidService};
use think\facade\{Cache, Validate};

class LifeServiceController extends BaseController
{
    protected $sidService;

    public function __construct()
    {
        parent::__construct(app());
        $this->sidService = new SidService();
    }

    /**
     * 获取生活服务列表
     */
    public function getServiceList()
    {
        try {
            $list = Cache::remember('life_service_list', function() {
                return LifeServiceConfig::where('status', 1)
                    ->order('sort desc, id asc')
                    ->field('business_type,service_name,service_desc')
                    ->select();
            }, 3600);
            
            return $this->success($list);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get service list failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取服务列表失败');
        }
    }

    /**
     * 获取活动列表
     */
    public function getActivityList()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'business_type' => 'require|number'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }

            $service = new JutuikeService();
            $list = $service->getActivityList($params['business_type']);
            return $this->success($list);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get activity list failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取活动列表失败');
        }
    }

    /**
     * 获取美团活动链接
     */
    public function getMeituanLink()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'type' => 'require|number',
                'act_id' => 'require'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 生成sid
            $sid = $this->sidService->generateSid($this->request->merchant_id, $user->id);
            
            $service = new JutuikeService();
            $data = $service->getMeituanActivityLink($params['type'], $sid, $params['act_id']);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get meituan link failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取美团活动链接失败');
        }
    }

    /**
     * 获取滴滴活动链接
     */
    public function getDidiLink()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'type' => 'require|number',
                'link_type' => 'require|in:all,mini,h5'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 生成sid
            $sid = $this->sidService->generateSid($this->request->merchant_id, $user->id);
            
            $service = new JutuikeService();
            $data = $service->getDidiActivityLink($params['type'], $sid, $params['link_type']);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get didi link failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取滴滴活动链接失败');
        }
    }

    /**
     * 获取抖音分类列表
     */
    public function getDouyinCategories()
    {
        try {
            $service = new JutuikeService();
            $data = $service->getDouyinCategories();
            return $this->success($data);
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get douyin categories failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取抖音分类失败');
        }
    }

    /**
     * 获取抖音活动链接
     */
    public function getDouyinLink()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'first_cateid' => 'require',
                'second_cateid' => 'require',
                'city_code' => 'require',
                'link_type' => 'require|in:all,mini,h5'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 生成sid
            $sid = $this->sidService->generateSid($this->request->merchant_id, $user->id);
            
            $service = new JutuikeService();
            $data = $service->getDouyinActivityLink($sid, $params['first_cateid'], 
                $params['second_cateid'], $params['city_code'], $params['link_type']);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get douyin link failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取抖音活动链接失败');
        }
    }

    /**
     * 领取优惠券
     */
    public function getCoupon()
    {
        try {
            $params = $this->request->post();
            
            $validate = Validate::rule([
                'service_type' => 'require|in:didi,meituan,ele',
                'merchant_id' => 'require|number'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            // 获取用户信息
            $userId = $this->request->user_id;
            $user = User::find($userId);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 调用聚推客服务
            $jutuikeService = new JutuikeService();
            $result = $jutuikeService->getCoupon($params['service_type'], $user);
            
            if (!$result['success']) {
                return $this->error($result['message']);
            }
            
            return $this->success($result['data']);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get coupon failed: %s',
                $e->getMessage()
            ));
            return $this->error('领取优惠券失败');
        }
    }

    /**
     * 获取推广链接
     */
    public function getPromotionUrl()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'service_type' => 'require|in:didi,meituan,ele'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $userId = $this->request->user_id;
            $user = User::find($userId);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            $jutuikeService = new JutuikeService();
            $result = $jutuikeService->getPromotionUrl($params['service_type'], $user);
            
            if (!$result['success']) {
                return $this->error($result['message']);
            }
            
            return $this->success($result['data']);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get promotion url failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取推广链接失败');
        }
    }

    /**
     * 获取拼多多频道活动链接
     */
    public function getPddChannelLink()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'resource_type' => 'require|in:4,39996,40000'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 生成sid
            $sid = $this->sidService->generateSid($this->request->merchant_id, $user->id);
            
            $service = new JutuikeService();
            $data = $service->getPddChannelLink($sid, $params['resource_type']);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get PDD channel link failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取拼多多频道活动链接失败');
        }
    }

    /**
     * 获取京东超级福利商品列表
     */
    public function getJdSubsidyGoods()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'page_index' => 'number|min:1',
                'page_size' => 'number|between:1,100',
                'goods_type' => 'in:0,1,2'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $service = new JutuikeService();
            $data = $service->getJdSubsidyGoods(
                $params['page_index'] ?? 1,
                $params['page_size'] ?? 20,
                $params['keyword'] ?? '',
                $params['goods_type'] ?? '0'
            );
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get JD subsidy goods failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取京东超级福利商品列表失败');
        }
    }

    /**
     * 获取京东商品/活动转链
     */
    public function getJdGoodsLink()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'goods_link' => 'require'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 生成sid
            $sid = $this->sidService->generateSid($this->request->merchant_id, $user->id);
            
            $service = new JutuikeService();
            $data = $service->getJdGoodsLink($params['goods_link'], $sid);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get JD goods link failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取京东商品/活动转链失败');
        }
    }

    /**
     * 获取电商聚合分类
     */
    public function getUnionCategories()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'source' => 'require|in:jd,pdd,taobao'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $service = new JutuikeService();
            $data = $service->getUnionCategories($params['source']);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get union categories failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取电商聚合分类失败');
        }
    }

    /**
     * 获取电商聚合商品列表
     */
    public function getUnionGoodsList()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'page' => 'number|min:1',
                'page_size' => 'number|between:1,100',
                'source' => 'require|in:jd,pdd,taobao',
                'sort' => 'in:0,1,2,3'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $service = new JutuikeService();
            $data = $service->getUnionGoodsList($params);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get union goods list failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取电商聚合商品列表失败');
        }
    }

    /**
     * 电商聚合搜索商品
     */
    public function searchUnionGoods()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'keyword' => 'require',
                'page' => 'number|min:1',
                'page_size' => 'number|between:1,100',
                'source' => 'in:jd,pdd,taobao',
                'sort' => 'in:0,1,2,3'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $service = new JutuikeService();
            $data = $service->searchUnionGoods($params['keyword'], $params);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Search union goods failed: %s',
                $e->getMessage()
            ));
            return $this->error('搜索电商聚合商品失败');
        }
    }

    /**
     * 电商聚合转链
     */
    public function getUnionGoodsLink()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'content' => 'require'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            // 生成sid
            $sid = $this->sidService->generateSid($this->request->merchant_id, $user->id);
            
            $service = new JutuikeService();
            $data = $service->getUnionGoodsLink($params['content'], $sid);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get union goods link failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取电商聚合转链失败');
        }
    }

    /**
     * 获取电商聚合平台列表
     */
    public function getUnionPlatforms()
    {
        try {
            $service = new JutuikeService();
            $data = $service->getUnionPlatforms();
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Get union platforms failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取电商聚合平台列表失败');
        }
    }

    /**
     * 检测粘贴板内容
     */
    public function checkUnionClipboard()
    {
        try {
            $params = $this->request->post();
            
            $validate = Validate::rule([
                'content' => 'require'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $service = new JutuikeService();
            $data = $service->checkUnionClipboard($params['content']);
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            LogService::error('LifeService', sprintf(
                'Check union clipboard failed: %s',
                $e->getMessage()
            ));
            return $this->error('检测粘贴板内容失败');
        }
    }

    /**
     * 获取滴滴业务类型
     */
    protected function getDidiBusinessType(int $type): int
    {
        $typeMap = [
            1 => 2, // 打车
            2 => 2, // 加油
            3 => 2, // 货运
            4 => 3, // 花小猪
            5 => 2  // 代驾
        ];
        return $typeMap[$type] ?? 2;
    }

    /**
     * 获取平台对应的业务类型
     */
    protected function getPlatformBusinessType(string $platform): int
    {
        $typeMap = [
            'jd' => 7,     // 京东
            'pdd' => 8,    // 拼多多
            'taobao' => 6  // 淘宝
        ];
        return $typeMap[$platform] ?? 6;
    }
} 